﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace T.Settlement.Repository
{
    /// <summary>
    /// 仓储实现
    /// </summary>
    public class SBaseRepository<T> : ISBaseRepository<T> where T : class, new()
    {
        private readonly SEFDbcontext _sEFdbcontext;
        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="sEFdbcontext"></param>
        public SBaseRepository(SEFDbcontext sEFdbcontext)
        {
            _sEFdbcontext = sEFdbcontext;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        public async Task<int> AddAsync(T entity)
        {
            await _sEFdbcontext.AddAsync(entity);
            return await _sEFdbcontext.SaveChangesAsync();
        }
        /// <summary>
        /// 查询全部
        /// </summary>
        /// <returns></returns>
        public async Task<List<T>> GetAllAsync()
        {
            return await _sEFdbcontext.Set<T>().ToListAsync();
        }
        /// <summary>
        /// 带条件查询
        /// </summary>
        /// <param name="expre"></param>
        /// <returns></returns>
        public Task<List<T>> GetAsync(Expression<Func<T, bool>> expre)
        {
            return _sEFdbcontext.Set<T>().Where(expre).ToListAsync();
        }
        /// <summary>
        /// 查询单条数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<T> GetModelAsync(int id)
        {
            return await _sEFdbcontext.Set<T>().FindAsync(id);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> Update(T entity)
        {
             _sEFdbcontext.Update(entity);
            return await _sEFdbcontext.SaveChangesAsync();
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public async Task<int> UpdateRange(List<T> entities)
        {
            _sEFdbcontext.UpdateRange(entities);
            return await _sEFdbcontext.SaveChangesAsync();
        }
    }
}
